import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess, useResponseError } from '~/utils/response';
import { queryDatabase, formatDateTime, creatDocxFile } from '~/functions';

const processField = (field: string) => {
  try {
    const parsed = JSON.parse(field);
    return Array.isArray(parsed) ? parsed : [parsed];
  } catch {
    return []; // 确保返回数组
  }
};

// 处理表格
const processCompInfoTable = (field: string) => {
  try {
    const rawData = JSON.parse(field);
    return Array.isArray(rawData) ? rawData : [rawData];
  } catch {
    return []; // 如果解析失败，返回空数组
  }
};

/*====================================================================================*/
export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) return unAuthorizedResponse(event);

  try {
    const { action, msdsNo } = await readBody(event);

    if (action === 'print') {
      if (!msdsNo) return useResponseError('MSDS编号不能为空！');
      const msdsData = <any[]>await queryDatabase('SELECT * FROM msdsData WHERE msdsNo = ?', [msdsNo]);
      if (msdsData.length === 0) return useResponseError('未找到该MSDS编号的数据！');

      const data = msdsData[0];
      const testData = {
        ...data,
        updateTime: formatDateTime(data.updateTime, 'date'),
        fillDate: formatDateTime(data.fillDate, 'dateCN'),
        component: processField(data.component),
        ghsHazClass: processField(data.ghsHazClass),
        compInfoTable: processCompInfoTable(data.compInfoTable),
        pictogram: processField(data.pictogram).map((name) => ({ image: name + '.png' })), // 转换为 { image: "xxx" } 格式
        pkgMark: processField(data.pkgMark).map((name) => ({ image: name + '.png' })),
      };
      const res = await creatDocxFile({
        docxTempName: 'MSDS_blank.docx',
        data: testData,
        outputName: msdsNo,
        convert: true,
        replace: {
          origin:
            /(<\/w:drawing><\/w:r><\/w:p><w:p\s+w14:paraId="[^"]+">\s*<w:pPr>(?:(?!<\/w:pPr>).)*?<\/w:rPr><\/w:pPr><w:r><w:rPr><w:rFonts\sw:hint="eastAsia")/g,
          target: '</w:drawing></w:r><w:r><w:rPr><w:rFonts w:hint="eastAsia"',
        },
      });
      // console.log('测试结果：', res);
      return useResponseSuccess({
        docx: '/output/' + msdsNo + '.docx',
        pdf: '/output/' + msdsNo + '.pdf',
      });
    }
  } catch (error) {
    // console.error('处理失败:', error);
    return useResponseError(error.message);
  }
});
